import { createSlice } from "@reduxjs/toolkit"
import { loginUser } from "../actions/authActions"

type AuthState = {
  loading: boolean
  userInfo: object
  userToken: string | null
  error: string | null
  isLoggedIn: boolean
}

const initialState: AuthState = {
  loading: false,
  userInfo: {}, // for user object
  userToken: null, // for storing the JWT
  error: null,
  isLoggedIn: false, // for monitoring the registration process.
}

const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    setLogin: (state, action) => {
        state.isLoggedIn= action?.payload?.isLoggedIn,
        state.userToken= action?.payload?.token
    },
    setLogout: (state) => {
        state.isLoggedIn=false,
        state.userToken= ''

    },
  },
  extraReducers: (builder) => {
    builder.addCase(loginUser.pending, (state, { payload }) => {
      state.loading = true
      state.error = null
    })
    builder.addCase(loginUser.fulfilled, (state, { payload }) => {
      state.loading = false
      state.isLoggedIn = true // login successful
      state.userToken = payload?.access
      state.error = null
      console.log("token", JSON.stringify(payload?.access, null, 2))
    })
    builder.addCase(loginUser.rejected, (state, { payload }) => {
      state.loading = false
      state.error = "Invalid Credentials"
      console.log("payload in rejected", JSON.stringify(payload, null, 2))
    })
  },
})

export default authSlice.reducer
export const { setLogin, setLogout } = authSlice.actions
